<?php

namespace app\index\model;

use app\service\Score;
use think\facade\Db;
use think\Model;

class Fake extends Model
{

    /**
     * @param int $fakeId 卡密
     * @param int $user_id 用户ID
     * $status 0添加积分卡密，1添加会员时长卡密，2商城卡密
     */
    public static function use($fakeId, $user_id)
    {
        $fakeData = self::where('fake', $fakeId)->find();
        $siteFakeArr = [0,1];
        if ($fakeData && $fakeData['status'] != 1 && in_array($fakeData['type'] , $siteFakeArr)) {
            $userData = Db::name('user')->where('id', $user_id)->find();
            $result = self::where('fake', $fakeId)->update(['status' => 1, 'use_uid' => $user_id]);
            if ($result) {
                switch ($fakeData['type']) {
                    case 0:
                        $score = $fakeData['num'];
                        $res = Score::add($user_id, $score);
                        $tip = "卡密使用成功,获得[$score]积分";
                        Msg::send(0,  $user_id, ['content' => $tip]);
                        break;
                    case 1:
                        $vip_time = $userData['vip_time'];
                        $add_vip_time = self::getFakeVipTime($fakeData['vip_time_type'], $fakeData['num']);
                        if (time() > $vip_time) {
                            $vip_time = time()  + $add_vip_time;
                        } else {
                            $vip_time = $userData['vip_time']  + $add_vip_time;
                        }
                        $tip = '卡密使用成功，vip时长将于' . date('Y-m-d H:i:s', $vip_time) . '过期';
                        Msg::send(0,  $user_id, ['content' => $tip]);
                        $res = User::where('id', $user_id)->update(['vip_time' => $vip_time]);
                        break;
                }
                return success([], $tip);
            }
        }
        else if (@$fakeData['status'] == 1) {
            return error('卡密已被使用');
        } else {
            return error('卡密不存在');
        }
        return error('异常错误，请联系管理员处理！');
    }
    public static function getFakeVipTime($type, $num)
    {
        switch ($type) {
            case '1':
                $time = 24 * 3600;
                break;
            case '2':
                $time = 24 * 3600 * 30;
                break;
            case '3':
                $time = 24 * 3600 * 365;
                break;
        }
        return $time * $num;
    }
    public static function getFake($type, $num) {}
}
